package com.lj.back.manage.scaffold.module.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lj.back.manage.scaffold.common.util.Assert;
import com.lj.back.manage.scaffold.module.sys.DO.SysUserTokenDO;
import com.lj.back.manage.scaffold.module.sys.constant.UserConstant;
import com.lj.back.manage.scaffold.module.sys.dao.SysUserTokenDao;
import com.lj.back.manage.scaffold.module.sys.service.SysUserTokenService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 用户token
 * @author lv
 * @version 1.0.0
 */
@Service
@AllArgsConstructor
public class SysUserTokenServiceImpl implements SysUserTokenService {

    private final SysUserTokenDao sysUserTokenDao;

    private QueryWrapper<SysUserTokenDO> getBaseQueryWrapper(){
        QueryWrapper<SysUserTokenDO> queryWrapper = new QueryWrapper();
        return queryWrapper;
    }

    @Override
    public boolean updateUserTokenExpireTime(String token, long expireTime) {
        if (checkTokenIsValid(token)){
            sysUserTokenDao.updateUserTokenExpireTime(token,expireTime);
        }
        return true;
    }

    @Override
    public boolean updateUserTokenExpireTime(String token) {
        sysUserTokenDao.updateUserTokenExpireTime(token, UserConstant.USER_TOKEN_DEFAULT_EXPIRE_TIME);
        return true;
    }

    @Override
    public boolean checkTokenIsValid(String token){
        Assert.assertNotNull(token,"token不能为空");
        QueryWrapper<SysUserTokenDO> queryWrapper = getBaseQueryWrapper();
        queryWrapper.eq("token",token);
        SysUserTokenDO sysUserTokenDO = sysUserTokenDao.selectOne(queryWrapper);
        if (sysUserTokenDO == null){
            return false;
        }
        boolean isInvalid = LocalDateTime.now().isAfter(sysUserTokenDO.getExpireTime());
        if (isInvalid){
            //删除token
            sysUserTokenDao.deleteById(sysUserTokenDO.getUserId());
            return false;
        }
        //续期
        updateUserTokenExpireTime(token);
        return true;
    }

    @Override
    public boolean deleteToken(String token){
        Assert.assertNotNull(token,"token不能为空");
        QueryWrapper<SysUserTokenDO> queryWrapper = getBaseQueryWrapper();
        queryWrapper.eq("token",token);
        sysUserTokenDao.delete(queryWrapper);
        return true;
    }

    @Override
    public boolean deleteToken(long userId){
        QueryWrapper<SysUserTokenDO> queryWrapper = getBaseQueryWrapper();
        queryWrapper.eq("user_id",userId);
        sysUserTokenDao.delete(queryWrapper);
        return true;
    }
}
